package com.sunny.ynhz.ui.base;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import butterknife.ButterKnife;

/**
 * Created by yangxianzhu on 2016/5/4 0004.
 */
public abstract class BaseFragmentWithViewPageroffLimit extends Fragment {
    /**
     * 当前是否可见
     */
    protected boolean isVisible = false;
    public LayoutInflater inflater;
    private View mContentView;
    /**
     * 是否已被加载过一次，第二次就不再去请求数据了
     */
    protected boolean hasLoaded = false;

    /**
     * 标志位，标志已经初始化完成
     */
    protected boolean isPrepared = false;
    public Bundle arguments;

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            isVisible = true;
            if (isVisible && isPrepared && !hasLoaded) {
                hasLoaded = true;
                initData();
                bindData();
            }
        } else {
            isVisible = false;
        }
    }

    public abstract void initData();


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        inflater = LayoutInflater.from(getActivity());
        mContentView = inflater.inflate(setLayoutResourceID(), null);//setContentView(inflater, container);
        ButterKnife.bind(this, mContentView);
        isPrepared = true;
        if (isVisible && isPrepared && !hasLoaded) {
            hasLoaded=true;
            initData();
            bindData();
        } else if (hasLoaded) {
            bindData();
        }
        return mContentView;
    }

    /**
     * 绑定数据
     */
    public abstract void bindData();

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        arguments = getArguments();
    }

    protected abstract int setLayoutResourceID();


}
